package pt.eden.tomcat.jms;

import pt.eden.tomcat.jms.ResourceFactory;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.RefAddr;
import javax.naming.Reference;
import java.util.Enumeration;
import java.util.Properties;

/**
 *
 */
public class GenericResourceFactoryImpl<T> implements ResourceFactory<T> {

    private String resourceName;

    public GenericResourceFactoryImpl(String resourceName) {
        this.resourceName = resourceName;
    }

    @Override
    @SuppressWarnings("unchecked")
    public T createReference(Reference reference) throws Exception {

        Properties properties = new Properties();
        String factoryName = null;

        Enumeration addresses = reference.getAll();
        while (addresses.hasMoreElements()) {
            RefAddr address = (RefAddr) addresses.nextElement();
            String addressName = address.getType();
            String addressValue = (String) address.getContent();

            if (addressName != null) {
                /* handle specific properties first */
                if (addressName.equalsIgnoreCase(this.resourceName)) {
                    factoryName = addressValue;
                } else {
                    /* if it's not a specific property, it will be used to create the initial context */
                    properties.put(addressName, addressValue);
                }
            }
        }

        if (properties.size() < 1) {
            throw new IllegalArgumentException("Environment not specified!");
        }

        if (factoryName == null) {
            throw new IllegalArgumentException("Resource name not specified (" + this.resourceName + ")!");
        }

        Context context = new InitialContext(properties);
        return (T) context.lookup(factoryName);
    }
}
